package com.example.demo.controller;

import com.example.demo.entity.Student;
import com.example.demo.service.StudentService;
import com.example.demo.vo.ResponseVO;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    // 1. 查询所有学生（分页）
    @GetMapping("/list")
    public ResponseVO list(@RequestParam(defaultValue = "1") int pageNum,
                           @RequestParam(defaultValue = "10") int pageSize,
                           @RequestParam(required = false) String keyword) {
        PageInfo<Student> pageInfo = studentService.listByPage(pageNum, pageSize, keyword);
        System.out.println("分页数据: " + pageInfo); // 打印分页数据
        return ResponseVO.success("查询成功", pageInfo);
    }

    // 2. 搜索学生
    @GetMapping("/search")
    public ResponseVO search(String keyword) {
        return ResponseVO.success("搜索完成", studentService.searchByName(keyword));
    }

    // 3. 通过ID查询
    @GetMapping("/{id}")
    public ResponseVO getById(@PathVariable Integer id) {
        Student student = studentService.getById(id);
        return student != null ?
                ResponseVO.success("查询成功", student) :
                ResponseVO.fail("学生不存在");
    }

    // 4. 新增学生
    @PostMapping
    public ResponseVO add(@RequestBody Student student) {
        int result = studentService.insert(student);
        return result > 0 ?
                ResponseVO.success("添加成功", student) :
                ResponseVO.fail("添加失败");
    }

    // 5. 修改学生
    @PutMapping
    public ResponseVO update(@RequestBody Student student) {
        int result = studentService.update(student);
        return result > 0 ?
                ResponseVO.success("修改成功", student) :
                ResponseVO.fail("修改失败");
    }

    // 6. 删除学生
    @DeleteMapping("/{id}")
    public ResponseVO delete(@PathVariable Integer id) {
        int result = studentService.delete(id);
        return result > 0 ?
                ResponseVO.success("删除成功", null) :
                ResponseVO.fail("删除失败");
    }
}
